/*
*/

#include "stm32f10x.h"


static void initGpio(void) {
    // ===== Pin Mux =====
    // PA8   | TIM1 CH1  - PWM1A
    // PB13  | TIM1 CH1N - PWM1B
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
    
    // ===== Configure GPIO =====
    // PWMxA as PWM output, PWMxB as normal GPIO
    GPIO_InitTypeDef st_g;
    
    st_g.GPIO_Speed = GPIO_Speed_50MHz;
    st_g.GPIO_Pin = GPIO_Pin_8;
    st_g.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOA, &st_g);
    
    st_g.GPIO_Pin = GPIO_Pin_13;
    GPIO_Init(GPIOB, &st_g);
    
    GPIO_WriteBit(GPIOB, GPIO_Pin_13, Bit_RESET);
    
}


static void initTim1(void) {
    TIM_TimeBaseInitTypeDef st_tb;
    TIM_OCInitTypeDef st_oc;
    
     RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
    
    // ===== Time base Config =====
    st_tb.TIM_Period = 999;
    st_tb.TIM_Prescaler = 72;
    st_tb.TIM_ClockDivision = TIM_CKD_DIV1;
    st_tb.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM1, &st_tb);
    
    // ===== PWM Output Config =====
    // channel 1
    st_oc.TIM_OCMode = TIM_OCMode_PWM1;
    st_oc.TIM_OutputState = TIM_OutputState_Enable;
    st_oc.TIM_Pulse = 50;
    st_oc.TIM_OCPolarity = TIM_OCPolarity_High;
    TIM_OC1Init(TIM1, &st_oc);
    TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
    
    
    // enable
    TIM_CtrlPWMOutputs(TIM1,ENABLE);
    TIM_ARRPreloadConfig(TIM1, ENABLE);
    TIM_Cmd(TIM1, ENABLE);
}


static void delay() {
    for (uint32_t n=0xFFFFF;n>0;n--) {}
}


void demo_tim1_main(void) {
    initGpio();
    initTim1();
    
    uint16_t ccr = 100;
    
    // to drive a motor runs
    while (1) {
        TIM_SetCompare1(TIM1, ccr);
        delay();
        
        ccr += 10;
        if (ccr > 400) {
            ccr = 50;
        }
    }
}
